from time import strftime

from pyecharts.charts import Bar, Grid, Map, Line, Pie, MapGlobe, Timeline, WordCloud
from pyecharts.charts.composite_charts import timeline
from pyecharts.globals import ThemeType
from pyecharts import options as opts
import pandas as pd
import re





def draw_map_total(map_name,data_bar_today,data_bar_total,data_line_total,data_pie,data_map_total,data_map_today,type,data_word):
        pieces = [
        {"min": 10000000},
        {"min": 1000000, "max": 9999999},
        {"min": 100000, "max": 999999},
        {"min": 10000, "max": 99999},
        {"min": 1000, "max": 9999},
        {"min": 0, "max": 999},
    ]

        piecesC = [
            {"min": 10000, 'color': '#7f1100'},
            {"min": 1000, "max": 9999, 'color': '#bd1316'},
            {"min": 500, "max": 999, 'color': '#e64b45'},
            {"min": 100, "max": 499, 'color': '#ff8c71'},
            {"min": 1, "max": 99, 'color': '#fdd2a0'},
            {"max": 0}
        ]

        bar = (Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
        .add_xaxis([i[0] for i in data_bar_today][2:])
        .add_yaxis('新增确诊',[i[1] for i in data_bar_today][2:])
        .add_yaxis('累计确诊',[i[1] for i in data_bar_total][2:])
       .set_global_opts(title_opts=opts.TitleOpts(title=map_name+'累计确诊人数条形图',
                                                  pos_left='6.2%',pos_top='2.2%',
                                                  title_textstyle_opts=opts.TextStyleOpts(font_size=14),



                                                  ),
                        legend_opts=opts.LegendOpts(pos_top='5.5%', pos_left='6%', is_show=True,
                                                    textstyle_opts=opts.TextStyleOpts(color='white')),
                        datazoom_opts=opts.DataZoomOpts(is_show=True,range_start=0,range_end=20,pos_top='45.9%',),
                        xaxis_opts=opts.AxisOpts(name='',
                                                 type_='category',  # 轴的类型
                                                 name_location='center',  # 坐标轴轴名称的位置
                                                 name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                 axislabel_opts=opts.LabelOpts(color='white',is_show=True),  # 坐标轴标签的颜色

                                                 axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                 is_inside=True,  # 刻度线是否朝内
                                                                                 # 坐标轴刻度线的样式
                                                                                 linestyle_opts=opts.LineStyleOpts(
                                                                                     color='cyan')),
                                                 axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],  # 坐标轴的箭头的方向
                                                                                 # 坐标轴轴线的颜色
                                                                                 linestyle_opts=opts.LineStyleOpts(
                                                                                     color='cyan'))
                                                 ),
                        yaxis_opts=opts.AxisOpts(name='人数',  # x轴的名称
                                                 type_='value',  # 轴的类型
                                                 name_location='center',  # 坐标轴轴名称的位置
                                                 name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                 axislabel_opts=opts.LabelOpts(color='cyan',is_show=False),  # 坐标轴标签的颜色
                                                 axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                 is_inside=True,  # 刻度线是否朝内
                                                                                 # 坐标轴刻度线的样式
                                                                                 linestyle_opts=opts.LineStyleOpts(
                                                                                     color='cyan')),
                                                 axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],  # 坐标轴的箭头的方向
                                                                                 # 坐标轴轴线的颜色
                                                                                 linestyle_opts=opts.LineStyleOpts(
                                                                                     color='cyan'))
                                                 ),
                        # ----- 视觉映射配置项目
                        visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                          is_show=False,
                                                          range_text=['Highe', 'Low'],
                                                          textstyle_opts=opts.TextStyleOpts(color='cyan'),

                                                          # 设置分段颜色
                                                          max_=10000,  # 最大值
                                                          pos_right='1%',
                                                          pos_top='center',
                                                          pieces=piecesC,
                                                          ),

                        )
       )
        line = (Line(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
            .add_xaxis([i[0] for i in data_line_total])
            .add_yaxis('确诊累计', [i[1] for i in data_line_total],
                       symbol='circle',
                       symbol_size=5,
                       label_opts=opts.LabelOpts(is_show=False),
                       is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                         data=[opts.MarkLineItem(type_='max')]))
            .add_yaxis('累计治愈', [i[2] for i in data_line_total],
                       symbol='circle',
                       symbol_size=5,
                       label_opts=opts.LabelOpts(is_show=False),
                       is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                         data=[opts.MarkLineItem(type_='max')]))
            .add_yaxis('累计死亡', [i[3] for i in data_line_total],
                       symbol='circle',
                       symbol_size=5,
                       label_opts=opts.LabelOpts(is_show=False),
                       is_smooth=True,
                       markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                         data=[opts.MarkLineItem(type_='max')]))
            .set_global_opts(
                                title_opts=opts.TitleOpts(title=map_name+'新增确诊人数时序折线图',
                                                  pos_left='5%',
                                                  title_textstyle_opts=opts.TextStyleOpts(font_size=14),pos_top='51%'),

                             xaxis_opts=opts.AxisOpts(name='日期',  # 坐标轴名称
                                                      name_gap=20,  # 坐标轴名称距离坐标轴的位置
                                                      name_textstyle_opts=opts.TextStyleOpts(color='cyan',  # 坐标轴名称字体颜色,
                                                                                             font_size=10),  # 字体大小
                                                      axislabel_opts=opts.LabelOpts(color='cyan'),  # 坐标轴标签的颜色
                                                      axisline_opts=opts.AxisLineOpts(is_show=True,  # 坐标轴轴线配置项目.
                                                                                      symbol=['none', 'arrow'],
                                                                                      # 设置右端箭头
                                                                                      #  设置轴线的颜色
                                                                                      linestyle_opts=opts.LineStyleOpts(
                                                                                          color='cyan')),
                                                      ),  # x轴配置项目结束
                             yaxis_opts=opts.AxisOpts(name='人数',  # 坐标轴名称
                                                      min_=0,
                                                      name_location='center',
                                                        name_gap=10,
                                                      name_textstyle_opts=opts.TextStyleOpts(color='cyan',  # 坐标轴名称字体颜色,
                                                                                             ),
                                                      axislabel_opts=opts.LabelOpts(color='cyan',is_show=False),  # 坐标轴标签的颜色
                                                      axisline_opts=opts.AxisLineOpts(is_show=True,  # 坐标轴轴线配置项目.
                                                                                      #  设置轴线的颜色
                                                                                      linestyle_opts=opts.LineStyleOpts(
                                                                                          color='cyan'),symbol=['none', 'arrow']),



                                                      ),
                             tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='cross'),
                             axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                                   label=opts.LabelOpts(color='black',
                                                                                        font_size=12,
                                                                                        font_family='SimHei')),
                             legend_opts=opts.LegendOpts(is_show=True,pos_bottom='42%',pos_left='4.2%'),


                             )
            .set_series_opts(linestyle_opts=opts.LineStyleOpts(color='pink',
                                                               width=2,
                                                               ))
            )

        name = pd.read_csv('translate.csv', encoding='utf-8')
        name_C = {i: j for i, j in zip([a for a in name['English']], [b for b in name['chinese']])}



        world_map = (
            Map(init_opts=opts.InitOpts(theme=ThemeType.CHALK,width='1400px', height='600px'))
            .add('total_confirm', data_map_total, type, is_map_symbol_show=False,
                 name_map=name_C)
            .add('today_confirm', data_map_today, type, is_map_symbol_show=False,
                 name_map=name_C)
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
            title_opts=opts.TitleOpts(title=map_name+'疫情地图', pos_left='center',
                                      subtitle_textstyle_opts=opts.TextStyleOpts(color='cyan',
                                                                                 font_family='KaiTi',
                                                                                 font_size=16)),
            visualmap_opts=opts.VisualMapOpts(max_=1000000, is_piecewise=True, pieces=pieces),
            legend_opts=opts.LegendOpts(pos_top='6%', textstyle_opts=opts.TextStyleOpts(color='black'), is_show=True,
                                        )
        )
    )

        pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.DARK))
       .add('',data_pie,
            radius=['40','100'],
            rosetype='area',
            center=['85.8%','79%'],
            label_opts=opts.LabelOpts(formatter="{b}:{c}人"),
            )
       .set_global_opts(title_opts=opts.TitleOpts(title=map_name+'累计确诊玫瑰图',
                                                  pos_right='8%',
                                                  title_textstyle_opts=opts.TextStyleOpts(font_size=14),
                                                 pos_top='57%'),
                        legend_opts=opts.LegendOpts(is_show=False))


       )


    #     piecesC = [
    #     {"min": 1000,'color':'#7f1100'},
    #     {"min": 100, "max": 999,'color':'#bd1316'},
    #     {"min": 50, "max": 99,'color':'#e64b45'},
    #     {"min": 10, "max": 49,'color':'#ff8c71'},
    #     {"min": 1, "max": 9,'color':'#fdd2a0'},
    #     { "max": 0,'color':'#B0E0E6'}
    # ]
    #对应字典


        china_map = (Map(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
            .add('today_confirm', data_map_today, type,
                label_opts=opts.LabelOpts(color='#fcfcfc', font_weight='bold', font_size=12,
                                                font_family='SimHei'), is_map_symbol_show=False)
            .add('total_confirm',data_map_total,type,
                 label_opts=opts.LabelOpts(color='#fcfcfc',font_weight='bold',font_size=12, font_family='SimHei'),is_map_symbol_show=False)
            # .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(title_opts=opts.TitleOpts(map_name+'疫情地图',pos_left='center',title_textstyle_opts=opts.TextStyleOpts(font_size=20, ),subtitle_textstyle_opts=opts.TextStyleOpts(font_size=16,color='white' ),pos_top='2%'),
                             legend_opts=opts.LegendOpts(pos_top='7%', textstyle_opts=opts.TextStyleOpts(color='white'), is_show=True,),
                             visualmap_opts=opts.VisualMapOpts(is_piecewise=True, pieces=piecesC, pos_left='5%', pos_top='center',range_text=['高', '低'],textstyle_opts=opts.TextStyleOpts(color='white')),
                             )
            )

        couldword = (
        WordCloud()
        .add('', data_pair=data_word, word_size_range=[20, 80],textstyle_opts=opts.TextStyleOpts(font_family='Microsoft YaHei', font_weight='bold',),pos_left='75%', pos_right='4%', pos_top='10%', pos_bottom='60%', height='300px', width='335px',shape='square')
        .set_global_opts(title_opts=opts.TitleOpts(title="疫情热点",
                                                           title_textstyle_opts=opts.TextStyleOpts(font_size=15),pos_right='12%',
                                                           pos_top='4%')))




        grid = Grid(init_opts=opts.InitOpts(theme=ThemeType.CHALK,width='1536px',height='700px'))
        grid.add(bar,opts.GridOpts(pos_left='2.6%',pos_right='77.6%',pos_top='10.5%',pos_bottom='54%'))
        grid.add(line,opts.GridOpts(pos_left ='2.6%', pos_right = '77.6%', pos_top ='58%', pos_bottom = '6%'))
        grid.add(pie,opts.GridOpts())
        grid.add(china_map,opts.GridOpts())
        grid.add(couldword,opts.GridOpts())
        grid.render(map_name+'.html')



######################################################################################################################
#全国各省
#获取处理完后的省的数据
dfP = pd.read_csv('city-province-data_2022_07_20.csv')
dfC = pd.read_csv('all_cities_data_2022_07_22.csv')
dfT = pd.read_csv('china_all_provinces_history_data_2022_07_19.csv')
province_list =set([ i for i in dfP['provinces']])
add_list = ['市','土家族苗族自治州','自治区','地区','区','林区','恩施公土家族苗族自治区','州','县'
        ,'朝鲜族自治州','新区','盟','县','傣族景颇族自治州','傈僳族自治州','藏族自治州','白族自治州','彝族自治州','哈尼族彝族自治州','壮族苗族自治州'
        ,'傣族自治州','藏族羌族自治州','哈萨克自治州','蒙古自治州','柯尔克孜自治州','回族自治州','苗族自治县','黎族自治县','布依族苗族自治州','苗族侗族自治州'
        ,'土家族苗族自治县','苗族土家族自治县','藏族自治州','蒙古族藏族自治州','','黎族苗族自治县','土家族自治县','兵团第八师','六师']

for province in province_list:
    data_pair1 = dfP[dfP['provinces']==province][['name', 'total_confirm']].values.tolist()
    data_pair2 = dfP[dfP['provinces']==province][['name', 'today_confirm']].values.tolist()
    data_pair3 = dfT[dfT['province_name'] == province][['date','total_confirm','total_heal','total_dead']].values.tolist()
    data_pair4 = dfC[dfC['provinces'] == province][['name', 'total_confirm']].values.tolist()
    data_pair5 = dfC[dfC['provinces'] == province][['name', 'today_confirm']].values.tolist()
    data_pair_word = [ tuple(i) for i in data_pair4]
    data_pairs1 =[[f"{i[0] + j}",i[1]] for i in data_pair1 for j in add_list]
    data_pairs2 = [[f"{i[0] + j}",i[1]] for i in data_pair2 for j in add_list]
    draw_map_total(province,data_pair5,data_pair4,data_pair3,data_pair4,data_pairs1,data_pairs2,province,data_pair_word)
# #中国带市的数据
#
partten = "省|特别行政区|林区|区|地区|市|蒙古自治州|哈萨克自治州|柯尔克孜自治州|\
蒙古族藏族自治州|彝族自治州|藏族自治州|藏族自治州|藏族羌族自治州|傈僳族自治州|\
朝鲜族自治州|土家族苗族自治州|苗族侗族自治州|布依族苗族自治州|哈尼族彝族自治州|\
傣族景颇族自治州|傣族自治州|黎族自治县|黎族苗族自治县|兵团第八师|自治州|州|六师"

df = pd.read_csv('all_cities_data_2022_07_19.csv')
df.loc[df[df['name'] == '琼中县']['name'].index,'name'] = '琼中'
df['name2'] = df['name'].apply(lambda x: x if len(x)<=2 else re.sub(partten,'',x))
data_pair = df[['name2','total_confirm']].values.tolist()
data_pair_ = df[['name2','today_confirm']].values.tolist()
data_pair_dict = dict(data_pair)
data_pair_dict_ = dict(data_pair_)
data_pair.extend([['双河',data_pair_dict['博尔塔拉']],
                  ['北屯',data_pair_dict['阿勒泰']],
                 ['铁门关',data_pair_dict['巴音郭楞']]
                 ])
data_pair_.extend([['双河',data_pair_dict['博尔塔拉']],
                  ['北屯',data_pair_dict['阿勒泰']],
                 ['铁门关',data_pair_dict['巴音郭楞']]
                 ])
df2 = pd.read_csv('china_all_provinces_data_now_2022_07_19.csv')
#准备折线图数据
data3 = pd.read_csv('world_all_country_history_data_2022_07_19.csv')
data_line_ = data3[data3['country_name'] == '中国'][['date','total_confirm','total_heal','total_dead']].values.tolist()[730:]




supply_prov = ['台湾','上海','天津','重庆','北京','澳门','香港']
supply_data = df2[df2['name'].apply(lambda x:x in supply_prov)][['name','total_confirm']].values.tolist()
supply_data_ = df2[df2['name'].apply(lambda x:x in supply_prov)][['name','today_confirm']].values.tolist()
data_pair.extend(supply_data)
data_pair_.extend(supply_data_)


data = pd.DataFrame({'城市':[data_pair[i][0] for i in range(len(data_pair))],'累计确诊':[data_pair[i][1] for i in range(len(data_pair))]})


data_pair = data[['城市','累计确诊']].sort_values(by='累计确诊',ascending=False).values.tolist()
print(data_pair)
data_word = [ tuple(i) for i in data_pair][2:]
print(data_word)

#
#
# draw_map_total(map_name='中国城市',data_bar_today=data_pair_[:30],data_bar_total=data_pair,
#                data_line_total=data_line_,data_pie=data_pair[:15],data_map_total=data_pair,data_map_today=data_pair_,
#                type='china-cities',data_word=data_word)